<template>
    <view>
        <uni-section title="district" type="line" subTitle="五级行政区划"></uni-section>
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-db">
					<picker mode="multiSelector" @columnchange="bindMultiPickerColumnChange" :value="multiIndex" :range="multiArray">
						<view class="uni-input">{{multiArray[0][multiIndex[0]]}} {{multiArray[1][multiIndex[1]]}} {{multiArray[2][multiIndex[2]]}} {{multiArray[3][multiIndex[3]]}} {{multiArray[4][multiIndex[4]]}}</view>
					</picker>
				</view>
			</view>
		</view>      
        <uni-section title="validate" type="line" subTitle="数据校验接口可查询数据是否有效，以及归属地等信息"></uni-section>
        <!-- <view style="padding-left: 27rpx;">
            <uni-combox label="数据类型" :candidates="candidates" v-model="select" @input="selectChange"></uni-combox>
        </view> -->
        <radio-group @change="selectChange">
            <radio value="mobile" checked="true">手机</radio>
            <radio value="plateNumber">车牌</radio>
            <radio value="idNumber">身份证</radio>
            <radio value="bankCardNumber">银行卡</radio>
            <radio value="ip">IP</radio>
        </radio-group>
        <input class="uni-input" placeholder="请输入" v-model="value" @input="inputChange" />
        <text class="example-info">{{msg}}</text>
        <uni-section title="checkcode" type="line" subTitle="验证码接口，支持简单图片验证码生成和校验"></uni-section>
        <radio-group @change="radioChange">
            <radio value="-2">字符</radio>
            <!-- <radio value="0">中文</radio> -->
            <radio checked="checked" value="1">算术</radio>
            <!-- <radio value="2">拆字</radio> -->
            <radio value="-1">随机</radio>
        </radio-group>
        <image :src="checkcode.imgSrc" mode="aspectFit" style="height: 120rpx;width:360rpx;padding-left: 27rpx;"></image>
        <uni-icons type="reload" color="#007aff" size="45" @click="imageClick"/>
        <input class="uni-input" placeholder="请输入" @input="checkChange" />
        <uni-icons type="check" color="#007aff" size="30"/>
        <text class="example-info">{{checkcode.msg}}</text>
        <view class="uni-hello-addfile" @click="chooseFile">+ 请选择文件<span v-if="tempFilePath">：{{tempFilePath}}</span></view>
        <button @click="uploadFile">action</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                candidates: ['手机号', '车牌号', '身份证号', '银行卡号', 'IP地址'],
                types: ['mobile', 'plateNumber', 'idNumber', 'bankCardNumber', 'ip'],
                select: '手机号',
                type: 'mobile',
                value: '',
                msg: '',
                checkcode: {
                    type: '1',
                    sid: '',
                    imgSrc: '',
                    msg: ''
                },
				multiArray: [['省'], ['市'], ['县'], ['乡'], ['村']],
				multiIndex: [0, 0, 0, 0, 0],
                multiCode: [[],[],[],[],[]],
                districtCode: '511623114202',
                tempFilePath: ''
            }
        },
        onReady() {
            // this.imageClick()
            this.districtLoad(this.districtCode, true, true)
        },
        methods: {
            selectChange: function(e) {
                console.log('select change:' + e)
                // this.type = this.types[this.candidates.indexOf(this.select)]
                this.type = e.detail.value
                this.value = ''
                this.msg = ''
                if (this.type == 'ip') {
                    uni.request({
                        url: getApp().globalData.api.service + '/ip/region.json',
                        success: res => {
                            if (res.data && res.data.ip) {
                                this.value = res.data.ip
                                this.msg = res.data.region
                            }
                        }
                    });
                }
            },
			bindMultiPickerColumnChange: function(e) {
				// console.log('修改的列为：' + e.detail.column + '，值为：' + e.detail.value)
                if(e.detail.column>0 && e.detail.value==0) return;
                this.multiIndex[e.detail.column] = e.detail.value
                this.districtCode = this.multiCode[e.detail.column][e.detail.value]
                this.districtLoad(this.districtCode,false,true)
				// this.$forceUpdate() //success方法里调用更合适
			},
            districtLoad(code,parent,child){
                uni.request({
                    url: getApp().globalData.api.service + '/district/query.json',
                    header: {'content-type':'application/json'},
                    data: {code:code,parents:parent,children:child},
                    success: (res) => {
                        this.districtArray(res.data['Province[]'], 0)
                        this.districtArray(res.data['City[]'], 1)
                        this.districtArray(res.data['County[]'], 2)
                        this.districtArray(res.data['Town[]'], 3)
                        this.districtArray(res.data['Village[]'], 4)
                        if(this.multiIndex[0]==0 && this.districtCode){
                            let multiIndex2 = [0, 0, 0, 0, 0] //加载初始值时计算multiIndex
                            if(this.districtCode.length>=2) multiIndex2[0] = this.multiCode[0].indexOf(this.districtCode.substr(0,2))
                            if(this.districtCode.length>=4) multiIndex2[1] = this.multiCode[1].indexOf(this.districtCode.substr(0,4))
                            if(this.districtCode.length>=6) multiIndex2[2] = this.multiCode[2].indexOf(this.districtCode.substr(0,6))
                            if(this.districtCode.length>=9) multiIndex2[3] = this.multiCode[3].indexOf(this.districtCode.substr(0,9))
                            if(this.districtCode.length==12) multiIndex2[4] = this.multiCode[4].indexOf(this.districtCode.substr(0,12))
                            this.multiIndex = multiIndex2
                        }
                        this.$forceUpdate()
                    }
                })
            },
            districtArray(array,index){
                if(!array) return;
                this.multiArray[index] = ['省市县乡村'.substr(index,1)]
                this.multiCode[index] = ['']
                console.log('更新'+this.multiArray[index][0])
                for(var i in array){
                    let pair = array[i]
                    this.multiArray[index].push(pair.name)
                    this.multiCode[index].push(pair.code)
                }
                for(var i=index+1;i<5;i++){
                    this.multiArray[i] = ['省市县乡村'.substr(i,1)]
                    this.multiCode[i] = ['']
                }
            },
            inputChange: function(e) {
                console.log('input change: ' + this.value + ', type: ' + this.type)
                this.msg = ''
                if (!this.value) {
                    return
                } else if ((this.type == 'mobile' && this.value.length < 3) ||
                    (this.type == 'plateNumber' && this.value.length < 2) ||
                    (this.type == 'idNumber' && this.value.length < 2) ||
                    (this.type == 'bankCardNumber' && this.value.length < 6) || (
                        this.type == 'ip' && !
                        /^((\d|[1-9]\d|[1]\d{2}|[2][0-4]\d|[2][5][0-5])\.){3}(\d|[1-9]\d|[1]\d{2}|[2][0-4]\d|[2][5][0-5])$/
                        .test(this.value))) {
                    this.msg = '无效'
                    return
                }
                uni.request({
                    url: getApp().globalData.api.service + '/validate.json',
                    data: {
                        type: this.type,
                        value: this.value
                    },
                    success: (res) => {
                        if (res.data) {
                            let data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
                            console.log(data)
                            this.msg = data.valid === 'true' ? '有效' : '无效'
                            if (data.region || data.text || data.area) {
                                this.msg += '，' + (data.region || data.text || data.area)
                            }
                            if (this.type == 'mobile' && !data.region && data.type) {
                                this.msg += data.type == '1' ? '，移动' : (data.type == '2' ? '，联通' : (
                                    data.type == '3' ? '，电信' : ''))
                            }
                            if (this.type == 'bankCardNumber' && data.cardName) {
                                this.msg += '，' + (data.bankName2 || bankName) + '，' + data.cardDigits +
                                    '位' + data.cardName
                            }
                        }
                    }
                });
            },
            radioChange: function(e){
                this.checkcode.type = e.detail.value
                this.imageClick()
            },
            imageClick: function(){
                this.checkcode.msg = ''
                this.checkcode.check = ''
                this.checkcode.sid = Date.now() + Math.random().toString().substr(3,7)
                this.checkcode.imgSrc = getApp().globalData.api.service+'/checkcode/image?sid='+this.checkcode.sid+'&type='+this.checkcode.type;
            },
            checkChange: function(e){
                this.checkcode.msg = ''
                let checkcode = e.detail.value
                if(!checkcode) return
                if(this.checkcode.check){//已得到正确答案时，可直接判断
                    this.checkcode.msg = checkcode==this.checkcode.check ? '正确' : '错误'
                    return
                }
                uni.request({
                    url: getApp().globalData.api.service+'/checkcode/check.json',
                    method: 'GET',
                    data: {sid: this.checkcode.sid,checkcode:checkcode},
                    success: res => {
                        this.checkcode.msg = res.data.valid==='true' ? '正确' : '错误'
                        if(res.data.valid==='true'){//缓存正确答案，刷新图片时清除
                            this.checkcode.check = checkcode
                        }
                    }
                });
            },
            chooseFile: function(e){
                uni.chooseFile({
                    count:1,
                    success: (res) => {
                        console.log(res)
                        this.tempFilePath = res.tempFilePaths[0];
                    }
                })
            },
            uploadFile: function(e){
                if(!this.tempFilePath || !this.tempFilePath.startsWith('blob')){
                    return;
                }
                uni.uploadFile({
                    url:getApp().globalData.api.service+'/upload.json',
                    name:'file',
                    filePath:this.tempFilePath,
                    formData:{
                        type:'file'
                    },
                    success:(res)=>{
                        console.log(res)
                        let data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
                        this.tempFilePath=data.path
                    }
                })
            }
        }
    }
</script>
<style>
    .uni-input {
        font-size: 16px;
        height: 22px;
        line-height: 22px;
        padding: 0 0 0 27rpx;
    }
    radio {
        font-size: 16px;
    }
</style>
